package com.sskj.level.presenter;

import com.google.gson.Gson;
import com.lzy.okgo.model.Response;
import com.sskj.common.base.HttpData;
import com.sskj.common.http.WebSocketObserver;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.util.DisposUtil;
import com.sskj.level.bean.SocketSendBean;
import com.sskj.level.http.HttpConfig;
import com.sskj.level.ui.fragment.FiveFragment;
import com.sskj.lib.Constans;
import com.sskj.lib.bean.WSFiveBean;
import com.sskj.lib.http.JsonCallBack;

import java.util.List;

import io.reactivex.disposables.Disposable;


public class FiveFragmentPresenter extends BasePresenter<FiveFragment> {


    private WebSocketObserver stockSocketFive;
    private Disposable stockDisposableFive;

    /**
     * 盘口
     *
     * @param code 币种标识符
     * @return
     */
    public void getPankou(String code) {
        httpService.getPankou(code).execute(new JsonCallBack<HttpData<List<WSFiveBean>>>() {
            @Override
            public void onSuccess(Response<HttpData<List<WSFiveBean>>> response) {
                HttpData<List<WSFiveBean>> httpData = response.body();
                if (httpData.getStatus() == HttpConfig.OK) {
                    mView.updateFive(httpData.getData().get(0));
                }
            }
        });
    }

    public void initSocket(String code) {
        if (stockSocketFive == null) {
            stockSocketFive = httpService.pushCoinFive(code);
            stockDisposableFive = stockSocketFive
                    .map(s -> new Gson().fromJson(s, WSFiveBean.class))
                    .subscribe(data -> RxBus.getDefault().post(data), e -> {

                    });
        } else {
            stockSocketFive.send(new Gson().toJson(new SocketSendBean(code)));
        }
    }

    public void sendCode(String code) {

        initSocket(code);
    }

    public void closeWebSocket() {
        stockSocketFive = null;

        DisposUtil.close(stockDisposableFive);
    }

}
